﻿using System;
using System.Data;
using System.ServiceModel;
using System.Windows.Forms;
using System.ComponentModel;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win.UltraWinGrid.ExcelExport;

namespace DMSClient
{
    public partial class FTP : Form
    {
        private DataTable dt, dtDistributorsProgress, dtTristateReport, dtTristateReportDetailed, dtDistributorsActivity, dtDistributorsStatus, dtUnileverStatus;
        private string ambient;
        private WSHttpBinding Binding;
        private EndpointAddress address;

        public FTP()
        {
            
            this.ambient = Properties.Settings.Default.CurrentEnv;

            Binding = new WSHttpBinding();
            Binding.MaxReceivedMessageSize = Int32.MaxValue;
            Binding.MaxBufferPoolSize = Int32.MaxValue;
            Binding.CloseTimeout = TimeSpan.MaxValue;
            Binding.ReceiveTimeout = TimeSpan.MaxValue;
            Binding.SendTimeout = TimeSpan.MaxValue;
            Binding.Security.Mode = SecurityMode.None;
            Binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;

            address = new EndpointAddress(Properties.Settings.Default.Server);

            this.ambient = Properties.Settings.Default.CurrentEnv;

            DMSServices.DMSServicesClient client = new DMSServices.DMSServicesClient(Binding, address);
            string respuesta = null;
            try
            {
                client.Open();
                respuesta = client.getDistributorsList(this.ambient);
                client.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ex.InnerException);
            }
            if (respuesta == null)
            {
                throw new Exception(Properties.Settings.Default.DistributorsNullListErrorMsg);
            }

            InitializeComponent();
            this.dtTristateReportDetailed = new DataTable();
            this.Text = Properties.Settings.Default.CurrentEnvDes + " - FTP Report";

            dt = new DataTable("dtDistributorsList");
            dt.Columns.Add("idOrgUnit", Type.GetType("System.Int64"));
            dt.Columns.Add("cdOrgUnit", Type.GetType("System.String"));

            DataSet dataSet = new DataSet();
            dataSet.Tables.Add(dt);
            System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
            dataSet.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();

            DataRow dr = dt.NewRow();
            dr[0] = -1;
            dr[1] = "ALL DISTRIBUTORS";
            dt.Rows.InsertAt(dr, 0);

            uceDistributors.DisplayMember = "cdOrgUnit";
            uceDistributors.ValueMember = "idOrgUnit";
            uceDistributors.DataSource = dt;
            uceDistributors.SelectedIndex = 0;
        }

        private void FTP_Load(object sender, EventArgs e)
        {
            udteStartDate.Value =
            udteEndDate.Value =
            udteStartDateDistributorsActivity.Value =
            udteEndDateDistributorsActivity.Value = 
            udteTriStateDetailed_Start.Value =
            udteTriStateDetailed_End.Value = DateTime.Now;
        }

        private void ubSearchDistributorProgress_Click(object sender, EventArgs e)
        {
            try { Int64.Parse(uneDistributorsProgress.Value.ToString()).ToString(); }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Please use a positive integer value of rows", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                uneDistributorsProgress.Focus();
                return;
            }
            activarDistributorsProgress(false);
            bgwSearchDistributorsProgress.RunWorkerAsync();
        }

        private void bgwSearchDistributorsProgress_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            DMSServices.DMSServicesClient client = new DMSServices.DMSServicesClient(Binding, address);
            string respuesta = null;
            try
            {
                client.Open();
                respuesta = client.getDistributorsFTPProgress(this.ambient, uneDistributorsProgress.Value.ToString());
                client.Close();
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.ReportErrorMsg, ex.InnerException);
            }
            if (respuesta == null)
            {
                throw new Exception(Properties.Settings.Default.ReportNullErrorMsg);
            }

            dtDistributorsProgress = new DataTable("dtDistributorsFTPProgress");
            dtDistributorsProgress.Columns.Add("cdlegalcode2", typeof(string));
            dtDistributorsProgress.Columns.Add("cdOrgUnit", typeof(string));
            dtDistributorsProgress.Columns.Add("RegionUser", typeof(string));
            dtDistributorsProgress.Columns.Add("Store", typeof(string));
            dtDistributorsProgress.Columns.Add("Visit", typeof(string));
            dtDistributorsProgress.Columns.Add("Quota", typeof(string));
            dtDistributorsProgress.Columns.Add("Route", typeof(string));
            dtDistributorsProgress.Columns.Add("Stock", typeof(string));
            dtDistributorsProgress.Columns.Add("CCFOT", typeof(string));
            dtDistributorsProgress.Columns.Add("Order", typeof(string));
            dtDistributorsProgress.Columns.Add("OrderItem", typeof(string));
            dtDistributorsProgress.Columns.Add("CabinetInventory", typeof(string));

            DataSet dataSet = new DataSet("dsDistributorsFTPProgress");
            dataSet.Tables.Add(dtDistributorsProgress);
            System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
            dataSet.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();
        }

        private void bgwSearchDistributorsProgress_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    activarDistributorsProgress(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                ugDistributorsProgress.DataSource = dtDistributorsProgress;
                activarDistributorsProgress(true);
            }
        }

        private void uneDistributorsProgress_ValueChanged(object sender, EventArgs e)
        {
            ugDistributorsProgress.DataSource = null;
        }

        private void FTP_Shown(object sender, EventArgs e)
        {
            centerLoaders();
        }

        private void FTP_Resize(object sender, EventArgs e)
        {
            centerLoaders();
        }

        private void centerLoaders()
        {
            loaderDistributorsProgress.Left = (this.Width - loaderDistributorsProgress.Width) / 2;
            loaderDistributorsProgress.Top = ((this.Height - loaderDistributorsProgress.Height) / 2) - loaderDistributorsProgress.Height;
            loaderTristateReport.Left = (this.Width - loaderTristateReport.Width) / 2;
            loaderTristateReport.Top = ((this.Height - loaderTristateReport.Height) / 2) - loaderTristateReport.Height;
            loaderDistributorsActivity.Left = (this.Width - loaderDistributorsActivity.Width) / 2;
            loaderDistributorsActivity.Top = ((this.Height - loaderDistributorsActivity.Height) / 2) - loaderDistributorsActivity.Height;
            loaderDistributorsStatus.Left = (this.Width - loaderDistributorsStatus.Width) / 2;
            loaderDistributorsStatus.Top = ((this.Height - loaderDistributorsStatus.Height) / 2) - loaderDistributorsStatus.Height;
            loaderUnileverStatus.Left = (this.Width - loaderUnileverStatus.Width) / 2;
            loaderUnileverStatus.Top = ((this.Height - loaderUnileverStatus.Height) / 2) - loaderUnileverStatus.Height;
            loaderTriStateDetailed.Left = (this.Width - loaderTriStateDetailed.Width) / 2;
            loaderTriStateDetailed.Top = ((this.Height - loaderTriStateDetailed.Height) / 2) - loaderTriStateDetailed.Height;
        }

        private void FTP_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (bgwSearchDistributorsProgress.IsBusy) bgwSearchDistributorsProgress.CancelAsync();
            if (bgwTristateReport.IsBusy) bgwTristateReport.CancelAsync();
            if (bgwDistributorsActivity.IsBusy) bgwDistributorsActivity.CancelAsync();
            if (bgwDistributorsStatus.IsBusy) bgwDistributorsStatus.CancelAsync();
            if (bgwUnileverStatus.IsBusy) bgwUnileverStatus.CancelAsync();
            if (bgwTriStateDetailed.IsBusy) bgwTriStateDetailed.CancelAsync();
        }

        private void FTP_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)27)
            {
                this.Close();
            }
        }

        private void ugDistributorsProgress_InitializeRow(object sender, Infragistics.Win.UltraWinGrid.InitializeRowEventArgs e)
        {
            try
            {
                int i;
                for (i = 2; i < e.Row.Cells.Count; i++)
                {
                    if (e.Row.Cells[i].Value.ToString().Equals("OK"))
                    {
                        e.Row.Cells[i].Appearance.BackColor = System.Drawing.Color.LightGreen;
                    }
                    else
                    {
                        e.Row.Cells[i].Value = "Lower";
                        e.Row.Cells[i].Appearance.BackColor = System.Drawing.Color.LightPink;
                    }
                }
            }
            catch (System.Exception ex)
            {
            }
        }

        private void Export(object sender, EventArgs e)
        {
            Infragistics.Win.UltraWinGrid.UltraGrid ug = null;
            string message = "No data to export";

            switch (ultraTabControl1.ActiveTab.Text)
            {
                case "Integration per distributor":
                    if (ugDistributorsProgress.Rows.Count < 1)
                    {
                        MessageBox.Show(this, message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                    ug = ugDistributorsProgress;
                    break;
                case "Tristate report":
                    if (ugTristateReport.Rows.Count < 1)
                    {
                        MessageBox.Show(this, message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                    ug = ugTristateReport;
                    break;
                case "Distributors activity":
                    if (ugDistributorsActivity.Rows.Count < 1)
                    {
                        MessageBox.Show(this, message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                    ug = ugDistributorsActivity;
                    break;
                case "Records loaded":
                    if (ugDistributorsStatus.Rows.Count < 1)
                    {
                        MessageBox.Show(this, message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                    ug = ugDistributorsStatus;
                    break;
                case "Unilever status":
                    if (ugUnileverStatus.Rows.Count < 1)
                    {
                        MessageBox.Show(this, message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                    ug = ugUnileverStatus;
                    break;
                case "Distributors detailed activity":
                    if (ugTriStateDetailed.Rows.Count < 1)
                    {
                        MessageBox.Show(this, message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                    ug = ugTriStateDetailed;
                    break;
            }
            SaveFileDialog dialogo = new SaveFileDialog();
            dialogo.DefaultExt = "xls";
            UltraGridExcelExporter Exporter = new UltraGridExcelExporter();
            if (dialogo.ShowDialog() == DialogResult.OK)
            {
                Exporter.Export(ug, dialogo.FileName);
                if (MessageBox.Show(this, "Do you want to open the file?", this.Text, MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(dialogo.FileName);
                }
            }
        }

        private void ubSearchTristrateReport_Click(object sender, EventArgs e)
        {
            if (DateTime.Parse(udteStartDate.Value.ToString()) > DateTime.Parse(udteEndDate.Value.ToString()))
            {
                MessageBox.Show(this, "End date must be higher than start date", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            activateTristateReport(false);
            bgwTristateReport.RunWorkerAsync();
        }

        private void bgwTristateReport_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            DMSServices.DMSServicesClient client = new DMSServices.DMSServicesClient(Binding, address);
            string respuesta = null;
            try
            {
                client.Open();
                respuesta = client.getTriStateFTPReport(this.ambient,
                                                        DateTime.Parse(udteStartDate.Value.ToString()),
                                                        DateTime.Parse(udteEndDate.Value.ToString()));
                client.Close();
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.ReportErrorMsg, ex.InnerException);
            }
            if (respuesta == null)
            {
                throw new Exception(Properties.Settings.Default.ReportNullErrorMsg);
            }

            dtTristateReport = new DataTable("dtTristateReport");
            dtTristateReport.Columns.Add("pais", typeof(string));
            dtTristateReport.Columns.Add("idregion", typeof(string));
            dtTristateReport.Columns.Add("cdOrgUnit", typeof(string));
            dtTristateReport.Columns.Add("ImportRegionUser", typeof(string));
            dtTristateReport.Columns.Add("ImportStore", typeof(string));
            dtTristateReport.Columns.Add("ImportVisit", typeof(string));
            dtTristateReport.Columns.Add("ImportQuota", typeof(string));
            dtTristateReport.Columns.Add("ImportRoute", typeof(string));
            dtTristateReport.Columns.Add("ImportStock", typeof(string));
            dtTristateReport.Columns.Add("ImportCCFOT", typeof(string));
            dtTristateReport.Columns.Add("ImportOrderInvoice", typeof(string));
            dtTristateReport.Columns.Add("ImportOrderItemInvoiceItem", typeof(string));
            dtTristateReport.Columns.Add("ImportCabinetInventory", typeof(string));

            DataSet dataSet = new DataSet("dsTristateReport");
            dataSet.Tables.Add(dtTristateReport);
            System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
            dataSet.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();

            dtTristateReport.Columns["pais"].Caption = "cdCountry";
            dtTristateReport.Columns["idregion"].Caption = "idRegion";
            dtTristateReport.Columns["ImportRegionUser"].Caption = "RegionUser";
            dtTristateReport.Columns["ImportStore"].Caption = "Store";
            dtTristateReport.Columns["ImportVisit"].Caption = "Visit";
            dtTristateReport.Columns["ImportQuota"].Caption = "Quota";
            dtTristateReport.Columns["ImportRoute"].Caption = "Route";
            dtTristateReport.Columns["ImportStock"].Caption = "Stock";
            dtTristateReport.Columns["ImportCCFOT"].Caption = "CCFOT";
            dtTristateReport.Columns["ImportOrderInvoice"].Caption = "OrderInvoice";
            dtTristateReport.Columns["ImportOrderItemInvoiceItem"].Caption = "OrderItemInvoiceItem";
            dtTristateReport.Columns["ImportCabinetInventory"].Caption = "CabinetInventory";
        }

        private void bgwTristateReport_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    activateTristateReport(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                ugTristateReport.DataSource = dtTristateReport;
                activateTristateReport(true);
            }
        }

        private void activarDistributorsProgress(bool value)
        {
            loaderDistributorsProgress.Visible = !value;
            ugbDistributorsProgress.Enabled = value;
            ugDistributorsProgress.Enabled = value;
        }

        private void activateTristateReport(bool value)
        {
            loaderTristateReport.Visible = !value;
            ugbTristateReport.Enabled = value;
            ugTristateReport.Enabled = value;
        }

        private void activateDistributorsActivity(bool value)
        {
            loaderDistributorsActivity.Visible = !value;
            ugbDistributorsActivity.Enabled = value;
            ugDistributorsActivity.Enabled = value;
        }

        private void activateDistributorsStatus(bool value)
        {
            loaderDistributorsStatus.Visible = !value;
            ugbDistributorsStatus.Enabled = value;
            ugDistributorsStatus.Enabled = value;
        }

        private void TristateReportDateChanged(object sender, EventArgs e)
        {
            ugTristateReport.DataSource = null;
        }

        private void ugTristateReport_InitializeRow(object sender, Infragistics.Win.UltraWinGrid.InitializeRowEventArgs e)
        {
            try
            {
                int i;
                for (i = 3; i < e.Row.Cells.Count; i++)
                {
                    switch (e.Row.Cells[i].Value.ToString())
                    {
                        case "":
                            e.Row.Cells[i].Value = "Not sent";
                            e.Row.Cells[i].Appearance.BackColor = System.Drawing.Color.LightGray;
                            break;
                        case "1":
                            e.Row.Cells[i].Value = "Error";
                            e.Row.Cells[i].Appearance.BackColor = System.Drawing.Color.LightPink;
                            break;
                        case "2":
                            e.Row.Cells[i].Value = "OK";
                            e.Row.Cells[i].Appearance.BackColor = System.Drawing.Color.LightGreen;
                            break;
                    }
                }
            }
            catch (System.Exception ex)
            {

            }
        }

        private void bgwDistributorsActivity_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            DMSServices.DMSServicesClient client = new DMSServices.DMSServicesClient(Binding, address);
            string respuesta = null;
            try
            {
                client.Open();
                respuesta = client.getDistributorsFTPActivity(this.ambient,
                                                              DateTime.Parse(udteStartDateDistributorsActivity.Value.ToString()),
                                                              DateTime.Parse(udteEndDateDistributorsActivity.Value.ToString()),
                                                              uceShowDate.Checked);
                client.Close();
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.ReportErrorMsg, ex.InnerException);
            }
            if (respuesta == null)
            {
                throw new Exception(Properties.Settings.Default.ReportNullErrorMsg);
            }

            dtDistributorsActivity = new DataTable("dtDistributorsActivity");
            dtDistributorsActivity.Columns.Add("pais", typeof(string));
            dtDistributorsActivity.Columns["pais"].Caption = "cdCountry";
            if (uceShowDate.Checked)
            {
                dtDistributorsActivity.Columns.Add("region", typeof(string));
                dtDistributorsActivity.Columns["region"].Caption = "idRegion";
                dtDistributorsActivity.Columns.Add("fecha", typeof(string));
                dtDistributorsActivity.Columns["fecha"].Caption = "Date";
            }
            else
            {
                dtDistributorsActivity.Columns.Add("idregion", typeof(string));
            }
            dtDistributorsActivity.Columns.Add("login", typeof(string));
            dtDistributorsActivity.Columns.Add("archivo", typeof(string));
            if (uceShowDate.Checked)
            {
                dtDistributorsActivity.Columns.Add("Exitosos", typeof(string));
                dtDistributorsActivity.Columns.Add("Fallidos", typeof(string));
            }
            else
            {
                dtDistributorsActivity.Columns.Add("Fallidos", typeof(string));
                dtDistributorsActivity.Columns.Add("Exitosos", typeof(string));
            }

            DataSet dataSet = new DataSet("dsDistributorsActivity");
            dataSet.Tables.Add(dtDistributorsActivity);
            System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
            dataSet.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();

            dtDistributorsActivity.Columns["login"].Caption = "cdOrgUnit";
            dtDistributorsActivity.Columns["archivo"].Caption = "FileName";
            dtDistributorsActivity.Columns["Fallidos"].Caption = "Fail";
            dtDistributorsActivity.Columns["Exitosos"].Caption = "Success";
        }

        private void bgwDistributorsActivity_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    activateDistributorsActivity(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                ugDistributorsActivity.DataSource = dtDistributorsActivity;
                activateDistributorsActivity(true);
            }
        }

        private void ubSearchDistributorsActivity_Click(object sender, EventArgs e)
        {
            if (DateTime.Parse(udteStartDateDistributorsActivity.Value.ToString()) > DateTime.Parse(udteEndDateDistributorsActivity.Value.ToString()))
            {
                MessageBox.Show(this, "End date must be higher than start date", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            activateDistributorsActivity(false);
            bgwDistributorsActivity.RunWorkerAsync();
        }


        private void changedDistributorsActivity(object sender, EventArgs e)
        {
            ugDistributorsActivity.DataSource = null;
        }

        private void bgwDistributorsStatus_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            DMSServices.DMSServicesClient client = new DMSServices.DMSServicesClient(Binding, address);
            string respuesta = null;
            try
            {
                client.Open();
                respuesta = client.getDistributorsFTPStatus(this.ambient);
                client.Close();
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.ReportErrorMsg, ex.InnerException);
            }
            if (respuesta == null)
            {
                throw new Exception(Properties.Settings.Default.ReportNullErrorMsg);
            }

            dtDistributorsStatus = new DataTable("dtDistributorsStatus");
            dtDistributorsStatus.Columns.Add("cdCountry", typeof(string));
            dtDistributorsStatus.Columns.Add("cdOrgUnit", typeof(string));
            dtDistributorsStatus.Columns.Add("idStatus", typeof(string));
            dtDistributorsStatus.Columns.Add("RegionUser", typeof(Int64));
            dtDistributorsStatus.Columns.Add("Store", typeof(Int64));
            dtDistributorsStatus.Columns.Add("Visit", typeof(Int64));
            dtDistributorsStatus.Columns.Add("Quota", typeof(Int64));
            dtDistributorsStatus.Columns.Add("Route", typeof(Int64));
            dtDistributorsStatus.Columns.Add("Stock", typeof(Int64));
            dtDistributorsStatus.Columns.Add("CCFOT", typeof(Int64));
            dtDistributorsStatus.Columns.Add("Order", typeof(Int64));
            dtDistributorsStatus.Columns.Add("OrderItem", typeof(Int64));
            dtDistributorsStatus.Columns.Add("CabinetInventory", typeof(Int64));

            DataSet dataSet = new DataSet("dsDistributorsStatus");
            dataSet.Tables.Add(dtDistributorsStatus);
            System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
            dataSet.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();

        }

        private void bgwDistributorsStatus_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    activateDistributorsStatus(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                ugDistributorsStatus.DataSource = dtDistributorsStatus;
                for (int i = 3; i < ugDistributorsStatus.DisplayLayout.Bands[0].Columns.Count; i++)
                {
                    ugDistributorsStatus.DisplayLayout.Bands[0].Columns[i].Format = "N0";
                    ugDistributorsStatus.DisplayLayout.Bands[0].Columns[i].CellAppearance.TextHAlign = Infragistics.Win.HAlign.Right;
                }
                activateDistributorsStatus(true);
            }
        }

        private void ubSearchDistributorsStatus_Click(object sender, EventArgs e)
        {
            activateDistributorsStatus(false);
            bgwDistributorsStatus.RunWorkerAsync();
        }

        private void activateUnileverStatus(bool value)
        {
            loaderUnileverStatus.Visible = !value;
            ugbUnileverStatus.Enabled = value;
            ugUnileverStatus.Enabled = value;
        }

        private void ubSearchugUnileverStatus_Click(object sender, EventArgs e)
        {
            activateUnileverStatus(false);
            bgwUnileverStatus.RunWorkerAsync();
        }

        private void bgwUnileverStatus_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            DMSServices.DMSServicesClient client = new DMSServices.DMSServicesClient(Binding, address);
            string respuesta = null;
            try
            {
                client.Open();
                respuesta = client.getUnileverFTPStatus(this.ambient);
                client.Close();
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.ReportErrorMsg, ex.InnerException);
            }
            if (respuesta == null)
            {
                throw new Exception(Properties.Settings.Default.ReportNullErrorMsg);
            }

            dtUnileverStatus = new DataTable("dtUnileverStatus");
            dtUnileverStatus.Columns.Add("cdCountry", typeof(string));
            dtUnileverStatus.Columns.Add("dsCountry", typeof(string));
            dtUnileverStatus.Columns.Add("City", typeof(Int64));
            dtUnileverStatus.Columns.Add("Channel", typeof(Int64));
            dtUnileverStatus.Columns.Add("Region", typeof(Int64));
            dtUnileverStatus.Columns.Add("Product", typeof(Int64));
            dtUnileverStatus.Columns.Add("Quota_BP", typeof(Int64));
            dtUnileverStatus.Columns.Add("Quota_ECO", typeof(Int64));
            dtUnileverStatus.Columns.Add("Quota_LPPC", typeof(Int64));
            dtUnileverStatus.Columns.Add("Quota_SS", typeof(Int64));
            dtUnileverStatus.Columns.Add("Cabinet", typeof(Int64));

            DataSet dataSet = new DataSet("dsUnileverStatus");
            dataSet.Tables.Add(dtUnileverStatus);
            System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
            dataSet.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();
        }

        private void bgwUnileverStatus_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    activateUnileverStatus(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                ugUnileverStatus.DataSource = dtUnileverStatus;
                for (int i = 2; i < ugUnileverStatus.DisplayLayout.Bands[0].Columns.Count; i++)
                {
                    ugUnileverStatus.DisplayLayout.Bands[0].Columns[i].Format = "N0";
                    ugUnileverStatus.DisplayLayout.Bands[0].Columns[i].CellAppearance.TextHAlign = Infragistics.Win.HAlign.Right;
                }
                activateUnileverStatus(true);
            }
        }

        private void AutoResizeColumns(object sender, InitializeLayoutEventArgs e)
        {
            foreach (UltraGridBand bands in e.Layout.Bands)
            {
                foreach (UltraGridColumn ugc in bands.Columns)
                {
                    ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
                }
            }
        }

        private void cleanTristateReportDetailedRows(object sender, EventArgs e)
        {
            dtTristateReportDetailed.Rows.Clear();
            ugTriStateDetailed.Invalidate();
            ugTriStateDetailed.Update();
        }

        private void ubSearchTriStateDetailed_Click(object sender, EventArgs e)
        {
            if (DateTime.Parse(udteTriStateDetailed_Start.Value.ToString()) > DateTime.Parse(udteTriStateDetailed_End.Value.ToString()))
            {
                MessageBox.Show(this, "End date must be higher than start date", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            cleanTristateReportDetailedRows(sender, e);
            activateTristateReportDetailed(false);
            bgwTriStateDetailed.RunWorkerAsync();
        }

        private void activateTristateReportDetailed(bool value)
        {
            loaderTriStateDetailed.Visible = !value;
            ugbTriSatateDetailed.Enabled = value;
            ugTriStateDetailed.Enabled = value;
        }

        private void bgwTriStateDetailed_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            DMSServices.DMSServicesClient client = new DMSServices.DMSServicesClient(Binding, address);
            string respuesta = null;
            try
            {
                client.Open();
                respuesta = client.getTriStateFTPReportDetailed(this.ambient,
                                                        Int32.Parse(uceDistributors.Value.ToString()),
                                                        DateTime.Parse(udteTriStateDetailed_Start.Value.ToString()),
                                                        DateTime.Parse(udteTriStateDetailed_End.Value.ToString()));
                client.Close();
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.ReportErrorMsg, ex.InnerException);
            }
            if (respuesta == null)
            {
                throw new Exception(Properties.Settings.Default.ReportNullErrorMsg);
            }

            dtTristateReportDetailed = new DataTable("dtTristateReportDetailed");

            dtTristateReportDetailed.Columns.Add("pais", typeof(string));
            dtTristateReportDetailed.Columns["pais"].Caption = "cdCountry";

            dtTristateReportDetailed.Columns.Add("idorgunit", typeof(string));

            dtTristateReportDetailed.Columns.Add("cdOrgUnit", typeof(string));

            dtTristateReportDetailed.Columns.Add("fecha", typeof(System.DateTime));
            dtTristateReportDetailed.Columns["fecha"].Caption = "Date";
            
            dtTristateReportDetailed.Columns.Add("ImportRegionUser0", typeof(int));
            dtTristateReportDetailed.Columns["ImportRegionUser0"].Caption = "Fail";
            
            dtTristateReportDetailed.Columns.Add("ImportRegionUser1", typeof(int));
            dtTristateReportDetailed.Columns["ImportRegionUser1"].Caption = "Success";
            
            dtTristateReportDetailed.Columns.Add("ImportStore0", typeof(int));
            dtTristateReportDetailed.Columns["ImportStore0"].Caption = "Fail";
            
            dtTristateReportDetailed.Columns.Add("ImportStore1", typeof(int));
            dtTristateReportDetailed.Columns["ImportStore1"].Caption = "Success";
            
            dtTristateReportDetailed.Columns.Add("ImportVisit0", typeof(int));
            dtTristateReportDetailed.Columns["ImportVisit0"].Caption = "Fail";
            
            dtTristateReportDetailed.Columns.Add("ImportVisit1", typeof(int));
            dtTristateReportDetailed.Columns["ImportVisit1"].Caption = "Success";
            
            dtTristateReportDetailed.Columns.Add("ImportQuota0", typeof(int));
            dtTristateReportDetailed.Columns["ImportQuota0"].Caption = "Fail";
            
            dtTristateReportDetailed.Columns.Add("ImportQuota1", typeof(int));
            dtTristateReportDetailed.Columns["ImportQuota1"].Caption = "Success";
            
            dtTristateReportDetailed.Columns.Add("ImportRoute0", typeof(int));
            dtTristateReportDetailed.Columns["ImportRoute0"].Caption = "Fail";
            
            dtTristateReportDetailed.Columns.Add("ImportRoute1", typeof(int));
            dtTristateReportDetailed.Columns["ImportRoute1"].Caption = "Success";
            
            dtTristateReportDetailed.Columns.Add("ImportStock0", typeof(int));
            dtTristateReportDetailed.Columns["ImportStock0"].Caption = "Fail";
            
            dtTristateReportDetailed.Columns.Add("ImportStock1", typeof(int));
            dtTristateReportDetailed.Columns["ImportStock1"].Caption = "Success";
            
            dtTristateReportDetailed.Columns.Add("ImportCCFOT0", typeof(int));
            dtTristateReportDetailed.Columns["ImportCCFOT0"].Caption = "Fail";
            
            dtTristateReportDetailed.Columns.Add("ImportCCFOT1", typeof(int));
            dtTristateReportDetailed.Columns["ImportCCFOT1"].Caption = "Success";
            
            dtTristateReportDetailed.Columns.Add("ImportOrderInvoice0", typeof(int));
            dtTristateReportDetailed.Columns["ImportOrderInvoice0"].Caption = "Fail";
            
            dtTristateReportDetailed.Columns.Add("ImportOrderInvoice1", typeof(int));
            dtTristateReportDetailed.Columns["ImportOrderInvoice1"].Caption = "Success";
            
            dtTristateReportDetailed.Columns.Add("ImportOrderItemInvoiceItem0", typeof(int));
            dtTristateReportDetailed.Columns["ImportOrderItemInvoiceItem0"].Caption = "Fail";
            
            dtTristateReportDetailed.Columns.Add("ImportOrderItemInvoiceItem1", typeof(int));
            dtTristateReportDetailed.Columns["ImportOrderItemInvoiceItem1"].Caption = "Success";

            dtTristateReportDetailed.Columns.Add("ImportCabinetInventory0", typeof(int));
            dtTristateReportDetailed.Columns["ImportCabinetInventory0"].Caption = "Fail";

            dtTristateReportDetailed.Columns.Add("ImportCabinetInventory1", typeof(int));
            dtTristateReportDetailed.Columns["ImportCabinetInventory1"].Caption = "Success";
            
            DataSet dataSet = new DataSet("dtTristateReportDetailed");
            dataSet.Tables.Add(dtTristateReportDetailed);
            System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
            dataSet.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();

            dtTristateReportDetailed.Columns["ImportCabinetInventory0"].ColumnName = "ImportCabinet0";
            dtTristateReportDetailed.Columns["ImportCabinetInventory1"].ColumnName = "ImportCabinet1";
        }

        private void bgwTriStateDetailed_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    activateTristateReportDetailed(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                ugTriStateDetailed.DataSource = dtTristateReportDetailed;
                activateTristateReportDetailed(true);
            }
        }

        private void ugTriStateDetailed_InitializeRow(object sender, InitializeRowEventArgs e)
        {
            e.Row.Cells["ImportRegionUser0"].Appearance.BackColor = System.Drawing.Color.LightGray;
            e.Row.Cells["ImportRegionUser1"].Appearance.BackColor = System.Drawing.Color.LightGray;

            e.Row.Cells["ImportVisit0"].Appearance.BackColor = System.Drawing.Color.LightGray;
            e.Row.Cells["ImportVisit1"].Appearance.BackColor = System.Drawing.Color.LightGray;

            e.Row.Cells["ImportStock0"].Appearance.BackColor = System.Drawing.Color.LightGray;
            e.Row.Cells["ImportStock1"].Appearance.BackColor = System.Drawing.Color.LightGray;

            e.Row.Cells["ImportCCFOT0"].Appearance.BackColor = System.Drawing.Color.LightGray;
            e.Row.Cells["ImportCCFOT1"].Appearance.BackColor = System.Drawing.Color.LightGray;

            e.Row.Cells["ImportOrderItemInvoiceItem0"].Appearance.BackColor = System.Drawing.Color.LightGray;
            e.Row.Cells["ImportOrderItemInvoiceItem1"].Appearance.BackColor = System.Drawing.Color.LightGray;
        }
    }
}